import { Component, OnInit } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { Platform,NavController  } from '@ionic/angular';
import { HttpClient,HttpHeaders,HttpErrorResponse } from "@angular/common/http";
import { ToastController } from '@ionic/angular';
import { AuthTokenService } from '@services/auth-token.service';
import { TranslateService } from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AutoLoginType } from '@services/common-service.service';
import { CustomToastProviderService,CustomToastOption } from '@common-components/common-toast/custom-toast-provider.service';
import { EventEmitterService,EventName } from '@services/event-emitter.service';

@Component({
  selector: 'app-fingerprint-setup',
  templateUrl: './fingerprint-setup.page.html',
  styleUrls: ['./fingerprint-setup.page.scss'],
})
export class FingerprintSetupPage implements OnInit {

  public appUserId:string;

  public i18n:any = {};

  constructor(private router: Router,
              private route: ActivatedRoute,
              public navController: NavController,
              public http:HttpClient,
              private faio: FingerprintAIO,
              private toastController: ToastController,
              private authTokenService:AuthTokenService,
              private customToastProviderService:CustomToastProviderService,
              private commonService:CommonService,
              private defaultLanguageService:DefaultLanguageService,
              private translate: TranslateService,
              private eventEmitterService:EventEmitterService,
              public loadingController: LoadingController) {
    this.i18n = this.commonService.initTranslate(['myAccount.setting.fingerprintSetup']); 
  }

  ngOnInit() {
    this.appUserId = this.authTokenService.getAppUserId();
  }

  back(){
    this.eventEmitterService.eventEmit.emit(EventName.TOUCH_ID_LOGIN_CHANGED);
    this.navController.back();
  }
  
  setupFingerprint(){
    this.faio.show({
        title: '',
        fallbackButtonTitle: 'Use Backup',
        disableBackup:true,
    }).then((result: any) => {
      if(result == "biometric_success"){
        this.enableFingerprint();
      }
    }).catch((error: any) => {
      console.log(error);
    });
  }

  async enableFingerprint(){
    const loading = await this.loadingController.create({
      cssClass: 'my-custom-class',
      message: 'Please wait...',

    });
    await loading.present();
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    var api = "/scm/app/enableOrCloseAutoLogin.do";
    var requestJson = {
      'autoLoginType':AutoLoginType.FINGER_PRINT,
      'appUserId':this.appUserId,
      'deviceId':this.authTokenService.getDeviceId(),
      'enable':true
    }
    this.http.post(api,requestJson,httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        let customToastOption:CustomToastOption = {
          icon:true,
          iconSuccess:true,
          message:this.i18n.setup_success,
          duration:2000
        }
        this.customToastProviderService.show(customToastOption);
        this.authTokenService.setLoginToken(response.responseBody.loginToken);
        this.back();
      }
      loading.dismiss();
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      loading.dismiss();
    });
  }
}
